package com.ruoyi.common.core.domain;

import com.ruoyi.common.core.utils.CryptoUtils;
import com.ruoyi.common.core.utils.Global;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AESTypeHandler extends BaseTypeHandler<Object> {
	
	/**
	* 非空字段加密
	*/
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) {
        try {
            if (StringUtils.isBlank((String) parameter)) return;
            ps.setString(i, CryptoUtils.encryptSymmetrically(Global.COLS_AES_SECRETKEY, null, (String) parameter, CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5));
        } catch (Exception e) {
        	System.out.println("mybatis字段加密异常");
        }
    }
    
    /**
	* 根据字段列名解密
	*/
    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String col = rs.getString(columnName);
        try {
            if (StringUtils.isBlank(col)) return col;
            return CryptoUtils.decryptSymmetrically(Global.COLS_AES_SECRETKEY, null, col, CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5);
        } catch (Exception e) {
        	System.out.println("mybatis字段解密异常");
        }
        return col;
    }

    /**
	* 根据字段索引解密
	*/
    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String col = rs.getString(columnIndex);
        try {
            if (StringUtils.isBlank(col)) return col;
            return CryptoUtils.decryptSymmetrically(Global.COLS_AES_SECRETKEY, null, col, CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5);
        } catch (Exception e) {
        	System.out.println("mybatis字段加密异常");
        }
        return col;
    }

    /**
	* 根据存储过程解密
	*/
    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String col = cs.getString(columnIndex);
        try {
            if (StringUtils.isBlank(col)) return col;
            return CryptoUtils.decryptSymmetrically(Global.COLS_AES_SECRETKEY, null, col, CryptoUtils.Algorithm.Encryption.AES_ECB_PKCS5);
        } catch (Exception e) {
        	System.out.println("mybatis字段解密异常");
        }
        return col;
    }

}

